package Interview;

/**
 * @author leiwenkang <leiwenkang@kuaishou.com>
 * Created on 2022-04-11
 */
public class Test04有序数组中数字出现的次数 {

    public static void main(String[] args) {
        int[] array = {1, 4, 6, 6, 6, 8, 9};
        System.out.println(calCount(array, 6));
    }

    public static int calCount(int[] array, int target) {
        if (array == null || array.length == 0) {
            return 0;
        }
        int left = findLeft(array, target);
        if (left == -1) {
            return 0;
        }
        int right = findRight(array, target);

        return right - left + 1;
    }

    public static int findLeft(int[] array, int target) {
        if (array == null || array.length == 0) {
            return -1;
        }

        int start = 0;
        int end = array.length - 1;
        while (start <= end) {
            int mid = start + (end - start) / 2;
            if (array[mid] < target) {
                start = mid + 1;
            } else if (array[mid] > target) {
                end = mid - 1;
            } else {
                if (mid == 0 || array[mid - 1] != target) {
                    return mid;
                } else {
                    end = mid - 1;
                }
            }
        }
        return -1;
    }

    public static int findRight(int[] array, int target) {
        if (array == null || array.length == 0) {
            return -1;
        }

        int start = 0;
        int end = array.length - 1;
        while (start <= end) {
            int mid = start + (end - start) / 2;
            if (array[mid] < target) {
                start = mid + 1;
            } else if (array[mid] > target) {
                end = mid - 1;
            } else {
                if (mid == array.length - 1 || array[mid + 1] != target) {
                    return mid;
                } else {
                    start = mid + 1;
                }
            }
        }
        return -1;
    }
}
